package org.jspar.temp;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JPanel;

import org.jspar.model.Terminal;
import org.jspar.tile.Position;
import org.jspar.tile.Rectangle;
import org.jspar.tile.Tile;

@SuppressWarnings("serial")
public class TileView extends JPanel {
	
	private static final int UNIT = 10;

	private GlobalRouting routing;
	private Rectangle bounds;

	private Expansion expansion;

	public TileView(GlobalRouting routing) {
		this.routing = routing;
		bounds = computeBoundingBox(routing.getHTileRoot());
		setOpaque(true);
		setBackground(Color.white);
	}
	
	private Rectangle computeBoundingBox(Tile t) {
		Rectangle r = null;
		for (Tile tile : t.allspace()) {
			if (r == null)
				r = tile.getBounds();
			else
				r = r.union(tile.getBounds());
		}
		return r;
	}
	
	@Override
	public Dimension getPreferredSize() {
		return new Dimension(bounds.width*UNIT, bounds.height*UNIT);
	}
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (Tile tile : routing.getHTileRoot().allspace()) {
			printTile(g, tile, Color.black, false);
		}
		for (Tile tile : routing.getVTileRoot().allspace()) {
			printTile(g, tile, Color.red, false);
		}
		if (expansion != null) {
			drawExpansion(g, expansion);
			for (Expansion e : expansion.getConnected()) {
				drawExpansion(g, e);
			}
		}
	}

	private void drawExpansion(Graphics g, Expansion expansion) {
		Path p = expansion.getBestPath();
		for (Tile tile : p.tiles()) {
			printTile(g, tile, Color.lightGray, true);
		}
		g.setColor(Color.black);
		for (Terminal t : expansion.net().terminals()) {
			Position po = t.getGlobalPosition();
			g.drawRect((po.x()-bounds.x)*UNIT-3, (po.y()-bounds.y)*UNIT-3, 6, 6);
		}
		Position last = null;
		for (Position po : p.getPoints()) {
			if (last != null)
				g.drawLine((last.x()-bounds.x)*UNIT, (last.y()-bounds.y)*UNIT,
						(po.x()-bounds.x)*UNIT, (po.y()-bounds.y)*UNIT);
			last = po;
		}
	}

	private void printTile(Graphics g, Tile tile, Color color, boolean isFill) {
		Rectangle re = new Rectangle((tile.x()-bounds.x)*UNIT, (tile.y()-bounds.y)*UNIT,
				tile.width()*UNIT, tile.height()*UNIT);
		TileInfo info = (TileInfo)tile.content();
		boolean isHorizontal = info.isHorizontal;
		if (!isHorizontal) {
			re = new Rectangle((tile.y()-bounds.y)*UNIT, (tile.x()-bounds.x)*UNIT,
					tile.height()*UNIT, tile.width()*UNIT);
		}
		if (info.getModule() != null) {
			if (isHorizontal) {
				g.setColor(Color.green);
				g.fillRect(re.x, re.y, re.width, re.height);
				g.setColor(Color.black);
				g.drawString(info.getModule().name(), re.x+5, re.y + re.height/2);
			}
		} else {
			g.setColor(color);
			if (isFill)
				g.fillRect(re.x, re.y, re.width, re.height);
			else
				g.drawRect(re.x, re.y, re.width, re.height);
		}
	}

	public void setExpansion(Expansion expansion) {
		this.expansion = expansion;
		repaint();
	}

}
